#!/bin/bash

set -e

if [[ -n "${RASTER_VISION_DEBUG}" ]]; then
    set -x
fi

function usage() {
    echo -n \
        "Usage: $(basename "$0") [style_tests|unit_tests|integration_tests|coverage]
Run linters and tests based on the provided argument.
"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    if [[ "${1:-}" == "--help" ]]; then
        usage
    else
        COMMAND=${1:-"all"}

        if [[ -n "${CI}" ]]; then
            case $COMMAND in
                "style_tests")
                    docker run \
                        --rm -t \
                        "raster-vision-${IMAGE_TYPE}" \
                        /opt/src/scripts/style_tests
                    ;;
                "unit_tests")
                    docker run \
                        -w "/opt/src" \
                        -v "$(pwd):/opt/src" \
                        --rm -t \
                        "raster-vision-${IMAGE_TYPE}" \
                        /opt/src/scripts/unit_tests
                    ;;
                "integration_tests")
                    docker run \
                        --rm -t \
                        "raster-vision-${IMAGE_TYPE}" \
                        /opt/src/scripts/integration_tests
                    ;;
                "coverage")
                    docker run \
                        -w "/opt/src" \
                        -v "$(pwd):/opt/src" \
                        --rm -t \
                        "raster-vision-${IMAGE_TYPE}" \
                        coverage xml --omit=/opt/data/* --skip-empty
                    ;;
                *)
                    echo "Invalid argument. Run --help for usage."
                    exit 1
                    ;;
            esac
        else
            # Local test suite runs against pytorch image by default
            IMAGE_TYPE=${IMAGE_TYPE:-pytorch}

            # Delete old coverage reports
            rm -f ./.coverage ./coverage.xml

            # Execute test suites
            ./scripts/style_tests
            ./scripts/unit_tests
            ./scripts/integration_tests

            # Create new coverage reports
            coverage xml --omit=/opt/data/* --skip-empty
        fi
    fi
fi
